<?php
namespace app\branch\controller;
use think\Controller;
use think\Session;
use think\Request;
/**
 * 分公司管理员管理
 */
class Manager extends Controller
{   
    use \app\common\traits\controller\TraitController;

     protected $beforeActionList = [
        'first',
        'checkLogin'=> ['except' => 'getlogin,postloginsuccess,getlogout,getlosspassword,getupdatepassword,postauthentication,postsavepsd,postsavecode,getinvitation'],
        'checkPermissions' =>['except' =>'getsetpassword,getmanagerinfo,postupdatenote,postupdatesetpsd,getsetpsdok,getlogin,postloginsuccess,getlogout,getlosspassword,getupdatepassword,postauthentication,postsavepsd,postsavecode,getinvitation']
    ];

    protected function checkPermissions()
    {
        $status=model('Managers')->getLoginUserInfo('status');
        if ($status<>0) {
            //$this->redirect('@manager/aaaa');
            view('index/nopermissions')->send();
            exit;
        }
    }
    // public function getaaaa()
    // {
    //     return view('/index/nopermissions');
    // }
    protected function checkLogin()
    {
        
        if (!model('Managers')->checkLogin()) {
            $this->redirect('@manager/login');
            exit;
        }
    }

    /**
     * [getLogin 登陆界面]
     * @return [type] [description]
     */
    public function getLogin()
    {
        //return view('/index/login');
        if (model('Managers')->checkLogin()) {
            $this->redirect('/manager/index');
        }else{
            return view('index/login');
        }
    }
    /**
     * [getIndex 管理员首页]
     * @return [type] [description]
     */
    public function getIndex()
    {
        //首页统计信息
        $lo_bran_id = model('Managers')->getLoginUserInfo('branch_id');
        $camp_num = db('camps')->where('branch_id',$lo_bran_id)->count();//营地数量
        $this->assign('camp_num',$camp_num);
        $campid = db('camps')->where('branch_id',$lo_bran_id)->column('id');
        $user_num = '';
        if (!empty($campid)) {
          $user_num = db('users')->where(['camp_id'=>['in',$campid]])->count();//用户数量
        }
        //halt($user_num);
        $this->assign('user_num',$user_num);
        $car_num = model('Caravancontrols')->where(['branch_id'=>$lo_bran_id])->count();//房车数量
        $this->assign('car_num',$car_num);
        $order_num = '';
        if (!empty($campid)) {
          //订单数量
          $order_num = model('Orders')->where(['camp_id'=>['in',$campid]])->count();
        }
        $this->assign('order_num',$order_num);
        return view('index/index');
    }
    /**
     * [postloginsuccess 登陆表单]
     * @return [type] [description]
     */
    public function postloginsuccess()
    {
        $account = input('post.account');
        $password = input('post.password');
        //图片验证码 
        $code=input('post.code');
        $captcha = new \think\captcha\Captcha(config('captcha'));
        if (!$captcha->check($code)) {
            return $this->error(lang('验证码错误'));
        }
        $re=model('Managers')->accountLogin($account,$password,false);
        //halt($re);
        $user_id=model('Managers')->getLoginUserInfo('id');
        if ($re===true) {
            model('Managers')->where('id',$user_id)->setField('login_session_id',session('manager.login_session_id'));
            return $this->success(lang('to  login  success'), '/manager/index');
        }else{
            return $this->error(model('Managers')->getError());
        }

    }
    /**
     * [getLogout 退出登录]
     * @return [type] [description]
     */
    public function getLogout()
    {
       if (model('Managers')->logout()) {
            return  view('index/login');
        }
    }

    ///////////////////////找回密码//////////////////////////
    /**
     * [getLossPassword 忘记密码界面]
     * @return [type] [description]
     */
    public function getLossPassword()
    {
        return view('index/backpassword');
    }
    /**
     * [postAuthentication 忘记密码表单]
     * @return [type] [description]
     */
    public function postAuthentication()
    {
        $phone = input('post.phone');
        //图片验证码 
        $code=input('post.code');
        $captcha = new \think\captcha\Captcha(config('captcha'));
        if (!$captcha->check($code)) {
            return $this->error(lang('验证码错误'));
        }
        $phone_code = input('post.phone_code');
        $se = session_id();
        if ($phone_code==session('code.num')&&$se==session('code.local')&&$phone==session('code.account')) {
            $this->redirect('/manager/updatepassword');
        }

    }
    /**
     * [getupdatePassword 修改密码界面]
     * @return [type] [description]
     */
    public function getupdatePassword()
    {
        return view('index/updatepassword');
    }
    /**
     * [postSavePsd 保存密码]
     * @return [type] [description]
     */
    public function postSavePsd()
    {
        $account = session('code.account');
        $now_psd = input('post.now_psd');
        $re_now_psd = input('post.re_now_psd');
        if ($re_now_psd===$now_psd) {
            $result=model("Managers")->where('branch_num',$account)->setField('password',md5($now_psd));
            if ($result) {
                session('code', null);
                $this->redirect('/manager/backpsdok');
            }
        }else{
            return $this->error(lang('新密码与确认密码不一致'));
        }   
    }
    /**
     * [postSaveCode 存取验证码]
     * @return [type] [description]
     */
    public function postSaveCode()
    {
        $account = input('post.phone');
        $local = session_id();
        $code = $this->getInvitation();
        session('code.account',$account);
        session('code.local', $local);
        session('code.num', $code);
        $foo = \services\SmsFactory::init('WmSms')->sendCaptcha($account,$code,'10');
        return view('index/backpassword');
    }
    /**
   * [getInvitation 生成验证码]
   * @param  integer $len  [description]
   * @param  integer $type [description]
   * @return [type]        [description]
   */
  private function getInvitation($len = 6, $type = 1)
    {
        switch ($type) {
            case 1:
                $codeSet = '0123456789';
                break;
            case 2:
                $codeSet = 'abcdefhijkmnpqrstuvwxyz';
                break;
            case 3:
                $codeSet = '2345678abcdefhijkmnpqrstuvwxyz';
                break;
            case 4:
                $codeSet = 'abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY';
                break;
            case 5:
                $codeSet = '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY';
                break;

            default:
                $codeSet = '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY';
                break;
        }

        return substr(str_shuffle(str_repeat($codeSet, $len)), 0, $len);
    }
    /**
     * [getSetPsdOk 找回密码成功界面]
     * @return [type] [description]
     */
    public function getbackPsdOk()
    {
       return view('index/backpasswordok');
    }

    ///////////////////管理员个人信息/////////////////////////  
    /**
     * [getManagerInfo 个人信息]
     * @return [type] [description]
     */
    public function getManagerInfo()
    {   
        $account = session('manager.account');
        //halt($account);
        $list = model('Managers')->where('branch_num',$account)->find();
        return view('index/managerinfo',['list'=>$list]);
    }
    /**
     * [postUpdateManagerInfo 更新个人信息]
     * @return [type] [description]
     */
    public function postUpdateManagerInfo()
    {
        $post_manager_info['branch_num'] = input('post.branch_num');
        $post_manager_info['name'] = input('post.name');
        $post_manager_info['branch_name'] = input('post.branch_name');
        $post_manager_info['id_card'] = input('post.id_card');
        $post_manager_info['email'] = input('post.email');
        $post_manager_info['phone'] = input('post.phone');
        $post_manager_info['address'] = input('post.address');

        $id = input('post.id');
        $manager = model('Managers')->updateManager($id, $post_manager_info);

        if ($manager) {

            return $this->success(lang('update manager success'), '/manager/managerinfo');
        } 
        return $this->error(lang('update manager failed'));
    }
    /**
     * [getSetPassword 设置密码界面]
     * @return [type] [description]
     */
    public function getSetPassword()
    {
        return view('index/setpassword');
    }
    /**
     * [postUpdateSetPsd 设置密码成功]
     * @return [type] [description]
     */
    public function postUpdateSetPsd()
    {
        $account = session('manager.account');
        $before_psd = input('post.before_psd');
        $re = model('Managers')->where('password',md5($before_psd))->find();
        if (empty($re)) {
            return $this->error(lang('before_psd is error'));
        }
        $now_psd = input('post.now_psd');
        $re_now_psd = input('post.re_now_psd');

        if ($re_now_psd===$now_psd) {
            $result=model("Managers")->where('branch_num',$account)->setField('password',md5($now_psd));
            if ($result) {
                $this->redirect('/manager/setpsdok');
            }
        }else{
            return $this->error(lang('新密码与确认密码不一致'));
        }       
    }
    /**
     * [getSetPsdOk 设置密码成功界面]
     * @return [type] [description]
     */
    public function getSetPsdOk()
    {
       return view('index/setpasswordok');
    }

    /////////////////////////管理员设置/////////////////////////////
    //说明状态status为1是普通管理员。为2锁定该管理员。0为总管理员///
    /**
     * [getManagerList 管理员列表]
     * @return [type] [总管理员默认不会显示]
     */
    public function getManagerList()
    {
        $list = model('Managers')->where('status','<>',0)->select(); 
        return view('manager/managerlist',['list'=>$list]);
    }
    /**
     * [getReadInfo 查看管理员信息]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function getReadInfo($id)
    {
        $list = model("Managers")->where('id',$id)->find();
        return view('manager/personinfo',['list'=>$list]);
    }
    /**
     * [postUpdateNote 修改备注信息]
     * @return [type] [description]
     */
    public function postUpdateNote()
    {
        $id = input('post.id');
        $note = input('post.note');
        $re=model("Managers")->where('id',$id)->setField('note',$note);
        if ($re) {
            return $this->success(lang('update success'),'/manager/managerlist');
        }
    }
    /**
     * [getAddManager 添加管理员信息界面]
     * @return [type] [description]
     */
    public function getAddManager()
    {
        return view('manager/manageradd');
    }
    /**
     * [postSaveManager 添加管理员]
     * @return [type] [description]
     */
    public function postSaveManager()
    {
        $manager = input('post.manager');
        $password = md5(input('post.password'));
        $psd = model('Managers')->where('status',0)->where('branch_num',$manager)->value('password');
        $branch_name = model('Managers')->where('status',0)->where('branch_num',$manager)->value('branch_name');
        if ($password<>$psd) {
            return $this->error(lang('没有添加权限'));
        }
        //默认添加时手机号即密码
        $post_manager_info['password'] = md5(input('post.branch_num'));
        $post_manager_info['branch_name'] = $branch_name;
        $post_manager_info['branch_id'] = model('Managers')->getLoginUserInfo('branch_id');
        $post_manager_info['email'] = input('post.email');
        $post_manager_info['branch_num'] = input('post.branch_num');
        $post_manager_info['name'] = input('post.name');
        $post_manager_info['note'] = input('post.note');
        $post_manager_info['status'] = 1;
        $re = model('Managers')->createManager($post_manager_info);
        if ($re) {
            //通知信息
            //model('Managers')->sendNotice($post_manager_info['email'],$post_manager_info['branch_num']);
            return $this->success(lang('add success'),'/manager/managerlist');
        }else{
            return $this->error(lang('add error'));
        }
    }
    /**
     * [postDelInfo 删除管理员信息]
     * @return [type] [description]
     */
    public function postDelInfo()
    {
        $ids=input('post.ids/a');
        //dump($ids);die;
        $account = session('manager.account');
        $z = model('Managers')->where('status',0)->value('branch_num');
        if ($account<>$z) {
            return $this->error(lang('没有删除权限'));
        }
        if (empty($ids)) {
          return $this->error(lang('delete is null')); 
        }
        if (model('Managers')->delManager($ids)) {
            return $this->success(lang('delete manager success'), '/manager/managerlist');
        }    
        return $this->error(lang('delete manager failed'));  
    }
    /**
     * [postSetStatus 设置管理员状态/锁定]
     * @return [type] [说明status为1是普通管理员。为2锁定该管理员。0为总管理员]
     */
    public function postSetStatus()
    {
        $ids=input('post.ids/a');
        //dump($ids);die;
        $account = session('manager.account');
        $z = model('Managers')->where('status',0)->value('branch_num');
        if ($account<>$z) {
            return $this->error(lang('没有锁定权限'));
        }
        if (empty($ids)) {
          return $this->error(lang('delete is null')); 
        }
        if (model('Managers')->setManagerStatus($ids,2)) {
            return $this->success(lang('setstaut manager success'), '/manager/managerlist');
        }    
        return $this->error(lang('setstaut manager failed'));
    }



    /**
     * [postSetStatus 管理员状态/解除锁定]
     * @return [type] [说明status为1是普通管理员。为2锁定该管理员。0为总管理员]
     */
    public function postRemoveStatus()
    {
        $ids=input('post.ids/a');
        //dump($ids);die;
        $account = session('manager.account');
        $z = model('Managers')->where('status',0)->value('branch_num');
        if ($account<>$z) {
            return $this->error(lang('没有解除锁定权限'));
        }
        if (empty($ids)) {
          return $this->error(lang('delete is null')); 
        }
        if (model('Managers')->setManagerStatus($ids,1)) {
            return $this->success(lang('removestaut manager success'), '/manager/managerlist');
        }    
        return $this->error(lang('removestaut manager failed'));
    }

}
